# LuckPay Web Manage System
#
# Copyright (c) 2016 Lucky Byte, Inc.
#
express = require 'express'
pgsql   = require 'pg'
uuid    = require 'uuid'
router = express.Router()
module.exports = router


router.get '/', (req, res, next) ->
    await pgsql.connect settings.pgsql_url, defer err, client, done
    if err then done(client); return next(err)

    # 手续费列表
    await client.query \
        "select * from pay_fee", defer err, result
    if err then done(client); return next(err)
    res.locals.fees = result.rows

    await client.query \
        "select * from pay_fee_set limit 1", defer err, result
    if err then done(client); return next(err)

    # 如果还没有配置，则自动生成默认配置
    if result.rows.length == 0
        await client.query \
            "insert into pay_fee_set (
                serial, uuid, t20_fee, notes
            ) values ($1, $2, $3, $4)", [
                1, uuid.v4(), null, '默认配置'
            ], defer err, result
        if err then done(client); return next(err)
        done()
        res.redirect '/fee/set'
    else
        done()
        res.render 'fee/set', record: result.rows[0]


router.post '/edit', (req, res, next) ->
    for k in ['uuid']
        return next(new Error("请求缺少参数[#{k}]")) if not req.body[k]

    await pgsql.connect settings.pgsql_url, defer err, client, done
    if err then done(client); return next(err)

    await client.query \
        "update pay_fee_set set t20_fee = $1, notes = $2
            where uuid = $3", [
            req.body.t20_fee, req.body.notes, req.body.uuid
        ], defer err, result
    if err then done(client); return next(err)
    done()
    res.redirect '/fee'
